//
//  XZSigninQRcodeVC.m
//  Teecloud
//
//  Created by PC on 2018/11/5.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZSigninQRcodeVC.h"
#import "XZEditVC.h"
#import "XZShowQRCodeVC.h"
#import "XZQRcode.h"
#import "XZSigninQRcodeCell.h"
@interface XZSigninQRcodeVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tabView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, assign) NSInteger pageIndex;
@end

@implementation XZSigninQRcodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"签到二维码";
    self.view.backgroundColor = kWhiteColor;
    [self addRightBarButtonWithFirstImage:[UIImage imageNamed:@"edict"] action:@selector(edictAction)];
    [self getLeaveInfo];
}
#pragma mark - Networking
- (void)getLeaveInfo{
    self.pageIndex = 0;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetSignQrcodeList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.tabView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *array = [XZQRcode mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.dataSource removeAllObjects];
                [weakself.dataSource addObjectsFromArray:array];
                [weakself.tabView.mj_footer endRefreshing];
                [weakself.tabView.mj_header endRefreshing];
                if (weakself.dataSource.count == 0) {
                    [weakself.tabView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.tabView reloadData];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
            
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
- (void)addMoreLeaveInfo{
    self.pageIndex ++;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetSignQrcodeList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                NSArray *newsArray = [XZQRcode mj_objectArrayWithKeyValuesArray:dataInfo];
                [weakself.dataSource addObjectsFromArray:newsArray];
                if (dataInfo.count>0) {
                    [weakself.tabView.mj_footer endRefreshing];
                    [weakself.tabView.mj_header endRefreshing];
                    [weakself.tabView reloadData];
                }else{//没有数据的时候就显示暂无数据
                    weakself.tabView.mj_footer.state = MJRefreshStateNoMoreData;
                }
                
            }else{
                [weakself.tabView.mj_footer endRefreshing];
                [weakself.tabView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.tabView.mj_footer endRefreshing];
            [weakself.tabView.mj_header endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}

#pragma mark - TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.tabView.mj_footer.hidden = self.dataSource.count > 0? NO:YES;
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakObject(self)
    XZSigninQRcodeCell *qrcodeCell = [tableView dequeueReusableCellWithIdentifier:@"QRCODE"];
    XZQRcode *model = self.dataSource[indexPath.row];
    qrcodeCell.model = model;
    qrcodeCell.QRCodeBlock = ^(NSString * _Nonnull identifer) {
        if ([identifer isEqualToString:@"DELETE"]) {//删除
            [weakself deleteQRCode:model.Id];
        }else if ([identifer isEqualToString:@"EDIT"]){//编辑
            XZEditVC *editVC = [[XZEditVC alloc]init];
            editVC.isEdit = YES;
            editVC.EditBlock = ^{
                [weakself getLeaveInfo];
            };
            editVC.model = model;
             editVC.title = @"编辑签到二维码";
            editVC.groupId = weakself.groupId;
            [weakself.navigationController pushViewController:editVC animated:true];
        }else if ([identifer isEqualToString:@"COPY"]){//复制
            XZEditVC *editVC = [[XZEditVC alloc]init];
            editVC.isEdit = NO;
            editVC.EditBlock = ^{
                [weakself getLeaveInfo];
            };
            //获取当前的年月日
            NSDate *date = [NSDate date];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateStyle:NSDateFormatterMediumStyle];
            [formatter setTimeStyle:NSDateFormatterShortStyle];
            [formatter setDateFormat:@"YYYY-MM-dd"];
            NSString *currentTime = [formatter stringFromDate:date];
            //将其模型中的年月日替换成当前的年月日
            NSString *StartTime = [model.StartTime stringByReplacingCharactersInRange:NSMakeRange(0, 10) withString:currentTime];
            NSString *endTime = [model.EndTime stringByReplacingCharactersInRange:NSMakeRange(0, 10) withString:currentTime];
            //更改其模型中的开始/结束时间
            model.StartTime = StartTime;
            model.EndTime = endTime;
            
            editVC.model = model;
            editVC.title = @"编辑签到二维码";
            editVC.groupId = weakself.groupId;
            [weakself.navigationController pushViewController:editVC animated:true];
        }else{//二维码QRCODE
            XZShowQRCodeVC *showQRCodeVC = [[XZShowQRCodeVC alloc]init];
            showQRCodeVC.model = model;
            [weakself.navigationController pushViewController:showQRCodeVC animated:true];
        }
    };
    return qrcodeCell;
}

//创建
- (void)edictAction{
    kWeakObject(self)
    XZEditVC *editVC = [[XZEditVC alloc]init];
    editVC.isEdit = NO;
    editVC.EditBlock = ^{
        [weakself getLeaveInfo];
    };
    editVC.title = @"创建签到二维码";
    editVC.groupId = self.groupId;
    [self.navigationController pushViewController:editVC animated:true];
}
//删除二维码
- (void)deleteQRCode:(NSString *)idStr{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:idStr forKey:@"Id"];
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=DeleteSignQrcode&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [weakself getLeaveInfo];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
    
}
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc]init];
    }
    return _dataSource;
}

- (UITableView *)tabView{
    if (!_tabView) {
        _tabView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT-kNavBarAndStatusBarHeight-kBottomSafeHeight) style:UITableViewStylePlain];
        _tabView.delegate = self;
        _tabView.dataSource = self;
        _tabView.rowHeight = 80.f;
        _tabView.showsVerticalScrollIndicator =false;
        _tabView.separatorStyle =UITableViewCellSeparatorStyleNone;
        [_tabView registerNib:[UINib nibWithNibName:NSStringFromClass([XZSigninQRcodeCell class]) bundle:nil] forCellReuseIdentifier:@"QRCODE"];
        //上下拉刷新
        _tabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getLeaveInfo)];
        _tabView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(addMoreLeaveInfo)];
        _tabView.mj_footer.hidden =YES;
        [self.view addSubview:_tabView];
    }
    return _tabView;
}


@end
